/**
 * @author Rid King
 * @since 2017-05-02
 * @version 0.0.0
 * @description 观察者
 */
'user strict';

import _Observable from './_observable.js'
import Operator from './operator.js'
import DebounceTimeOperator from './operators/debounce-time.js'
import TimeoutOperator from './operators/timeout.js'
import FilterOperator from './operators/filter.js'

class Observable extends _Observable {
    /**
     * @description 注册生产者
     * @param producer <Producer> 生产者
     * @return <Observable>
    */
    static registerProducer (producer) {
        if (producer instanceof Producer) {
            Observable[producer.name] = producer.build()
        }

        return this
    }

    /**
     * @description 注册操作符
     * @param SubOperator <Operator> 操作符类
     * @return <Observable>
    */
    static registerOperator (SubOperator) {
        if (SubOperator.prototype instanceof Operator) {
            // 添加至原型链
            Observable.prototype[SubOperator.getName()] = function () {
                return new Observable((observer) => {
                    // 生成操作符对象
                    let operatorObserver = new SubOperator(observer, arguments)
                    // 返回取消订阅值
                    return this.subscribe(operatorObserver)
                })
            }
        }

        // Observable.prototype.map = function (project) {
        //     return new Observable((observer) => {
        //         const mapObserver = {
        //             next: (x) => observer.next(project(x)),
        //             error: (err) => observer.error(err),
        //             complete: () => observer.complete()
        //         };
        //         return this.subscribe(mapObserver);
        //     });
        // };

        return this
    }
}

/* 添加操作符 */
Observable.registerOperator(DebounceTimeOperator)
        .registerOperator(TimeoutOperator)
        .registerOperator(FilterOperator)

export default Observable